<script setup>
import { ref, onMounted, computed, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { useDocumentStore } from '@/stores/document';
import http from '@/utils/http';
// 导入Element Plus的消息组件
import { ElMessage, ElMessageBox } from 'element-plus';

const router = useRouter();
const userStore = useUserStore();
const documentStore = useDocumentStore();

// 分页参数
const currentPage = ref(1);
const pageSize = ref(10);
const totalPages = computed(() => Math.ceil(documentStore.totalDocuments / pageSize.value));

// 搜索参数
const searchQuery = ref('');

// 排序参数
const sortOptions = [
  { label: '最近更新', value: 'updateTime,desc' },
  { label: '创建时间', value: 'createTime,desc' },
  { label: '标题 A-Z', value: 'title,asc' },
  { label: '标题 Z-A', value: 'title,desc' }
];
const currentSort = ref(sortOptions[0].value);

// 加载状态
const loading = ref(false);

// 存储每个文档的用户权限
const documentPermissions = reactive({});

// 获取用户对特定文档的权限
const fetchDocumentPermission = async (documentId) => {
  try {
    // 获取文档的协作者列表
    const response = await http.post(`/documentUser/list`, {
      documentId
    });
    
    const collaborators = response.data;
    const currentUserId = userStore.currentUser?.id;
    
    // 默认权限为viewer
    let permission = 'viewer';
    
    // 检查当前用户是否是文档的创建者
    const document = documentStore.documents.find(doc => doc.id === documentId);
    if (document && document.userId === currentUserId) {
      permission = 'admin';
    } else {
      // 在协作者列表中查找当前用户
      const userCollaborator = collaborators.find(c => String(c.userId) === String(currentUserId));
      if (userCollaborator) {
        permission = userCollaborator.permission;
      }
    }
    
    // 存储权限
    documentPermissions[documentId] = permission;
    return permission;
  } catch (err) {
    console.error(`Failed to fetch permission for document ${documentId}:`, err);
    // 出错时默认为viewer权限
    documentPermissions[documentId] = 'viewer';
    return 'viewer';
  }
};

// 获取文档列表
const fetchDocuments = async () => {
  loading.value = true;
  try {
    await documentStore.fetchDocuments(currentPage.value, pageSize.value);
    
    // 获取每个文档的权限
    for (const doc of documentStore.documents) {
      await fetchDocumentPermission(doc.id);
    }
  } catch (error) {
    console.error('Failed to fetch documents:', error);
  } finally {
    loading.value = false;
  }
};

// 创建新文档
const createNewDocument = () => {
  router.push('/documents/create');
};

// 查看文档详情
const viewDocument = (documentId) => {
  router.push(`/documents/${documentId}`);
};

// 检查用户是否有权限删除文档
const canDeleteDocument = (documentId) => {
  const permission = documentPermissions[documentId];
  // 只有admin和editor权限可以删除文档，viewer权限不能删除
  return permission && (permission === 'admin' || permission === 'editor');
};

// 删除文档
const deleteDocument = async (documentId, event) => {
  // 阻止事件冒泡，避免触发卡片点击事件
  event.stopPropagation();
  
  // 检查权限
  if (!canDeleteDocument(documentId)) {
    ElMessage({
      type: 'warning',
      message: '您没有权限删除此文档'
    });
    return;
  }
  
  // 使用Element Plus的MessageBox进行确认操作
  ElMessageBox.confirm(
    '确定要删除这个文档吗？此操作不可撤销。',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      // 用户点击确认，执行删除操作
      loading.value = true;
      try {
        const success = await documentStore.deleteDocument(documentId);
        if (success) {
          // 刷新文档列表
          await fetchDocuments();
          // 显示成功消息
          ElMessage({
            type: 'success',
            message: '文档删除成功'
          });
        }
      } catch (error) {
        console.error('Failed to delete document:', error);
        // 显示错误消息
        ElMessage({
          type: 'error',
          message: '删除文档失败'
        });
      } finally {
        loading.value = false;
      }
    })
    .catch(() => {
      // 用户取消操作
      ElMessage({
        type: 'info',
        message: '已取消删除'
      });
    });
};

// 处理页码变化
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchDocuments();
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1; // 重置到第一页
  fetchDocuments();
};

// 处理排序变化
const handleSortChange = () => {
  fetchDocuments();
};

// 组件挂载时获取数据
onMounted(() => {
  fetchDocuments();
});
</script>

<template>
  <div class="document-list-container">
    <div class="document-list-header">
      <h1 class="page-title">我的文档</h1>
      <button @click="createNewDocument" class="create-doc-btn">
        <span class="icon">+</span> 新建文档
      </button>
    </div>

    <div class="document-list-filters">
      <div class="search-box">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索文档..."
          @keyup.enter="handleSearch"
        />
        <button @click="handleSearch" class="search-btn">搜索</button>
      </div>

      <div class="sort-box">
        <label for="sort">排序：</label>
        <select id="sort" v-model="currentSort" @change="handleSortChange">
          <option v-for="option in sortOptions" :key="option.value" :value="option.value">
            {{ option.label }}
          </option>
        </select>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-placeholder">
      <p>加载中...</p>
    </div>

    <!-- 空状态 -->
    <div v-else-if="documentStore.documents.length === 0" class="empty-state">
      <p>您还没有创建任何文档</p>
      <button @click="createNewDocument" class="btn-primary">创建第一个文档</button>
    </div>

    <!-- 文档列表 -->
    <div v-else class="documents-grid">
      <div 
        v-for="doc in documentStore.documents" 
        :key="doc.id" 
        class="document-card"
        @click="viewDocument(doc.id)"
      >
        <div class="document-card-content">
          <h3 class="document-title">{{ doc.title }}</h3>
          <p class="document-meta">
            <span class="document-date">最后编辑: {{ new Date(doc.updateTime).toLocaleDateString() }}</span>
          </p>
        </div>
        <div class="document-card-actions">
          <button 
            class="delete-btn" 
            @click="deleteDocument(doc.id, $event)"
            title="删除文档"
            :disabled="!canDeleteDocument(doc.id)"
            :class="{'disabled-btn': !canDeleteDocument(doc.id)}"
          >
            删除
          </button>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="documentStore.documents.length > 0" class="pagination">
      <button 
        :disabled="currentPage === 1" 
        @click="handlePageChange(currentPage - 1)"
        class="pagination-btn"
      >
        上一页
      </button>
      
      <span class="pagination-info">{{ currentPage }} / {{ totalPages }}</span>
      
      <button 
        :disabled="currentPage === totalPages" 
        @click="handlePageChange(currentPage + 1)"
        class="pagination-btn"
      >
        下一页
      </button>
    </div>
  </div>
</template>

<style scoped>
.document-list-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
  background-color: #f9fafb;
  color: #374151;
  min-height: calc(100vh - 120px);
}

.document-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2.5rem;
  padding-bottom: 1.5rem;
  border-bottom: 1px solid #e5e7eb;
}

.page-title {
  font-size: 2rem;
  font-weight: 700;
  color: #111827;
  margin: 0;
  position: relative;
  padding-left: 0.5rem;
}

.page-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0.25rem;
  bottom: 0.25rem;
  width: 4px;
  background: linear-gradient(to bottom, #4f46e5, #7c3aed);
  border-radius: 4px;
}

.create-doc-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1.75rem;
  background-color: #4f46e5;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.2);
}

.create-doc-btn:hover {
  background-color: #4338ca;
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(79, 70, 229, 0.3);
}

.create-doc-btn .icon {
  font-size: 1.25rem;
  font-weight: 600;
}

.document-list-filters {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
  background-color: white;
  padding: 1.25rem;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.search-box {
  display: flex;
  gap: 0.75rem;
  flex: 1;
  max-width: 450px;
}

.search-box input {
  flex: 1;
  padding: 0.75rem 1rem;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  font-size: 1rem;
  transition: all 0.3s ease;
  background-color: #f9fafb;
}

.search-box input:focus {
  outline: none;
  border-color: #4f46e5;
  box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
  background-color: white;
}

.search-btn {
  padding: 0.75rem 1.25rem;
  background-color: #4f46e5;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 8px rgba(79, 70, 229, 0.15);
}

.search-btn:hover {
  background-color: #4338ca;
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(79, 70, 229, 0.25);
}

.sort-box {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.sort-box label {
  font-size: 0.875rem;
  color: #4b5563;
  font-weight: 500;
}

.sort-box select {
  padding: 0.625rem 1rem;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  font-size: 0.875rem;
  background-color: #f9fafb;
  color: #4b5563;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 140px;
  appearance: none;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%236b7280'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 9l-7 7-7-7'%3E%3C/path%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 0.75rem center;
  background-size: 1rem;
  padding-right: 2.5rem;
}

.sort-box select:focus {
  outline: none;
  border-color: #4f46e5;
  box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
  background-color: white;
}

.sort-box select:hover {
  border-color: #9ca3af;
  background-color: white;
}

/* 文档卡片样式 */
.documents-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 1.5rem;
  margin-bottom: 2.5rem;
}

.document-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
  height: 160px;
  display: flex;
  flex-direction: column;
  position: relative;
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.document-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
  border-color: rgba(79, 70, 229, 0.2);
}

.document-card::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 4px;
  background: linear-gradient(to right, #4f46e5, #7c3aed);
  transform: scaleX(0);
  transform-origin: left;
  transition: transform 0.3s ease;
}

.document-card:hover::after {
  transform: scaleX(1);
}

.document-card-content {
  padding: 1.5rem;
  flex: 1;
  display: flex;
  flex-direction: column;
  position: relative;
  z-index: 1;
}

.document-title {
  font-size: 1.125rem;
  font-weight: 600;
  color: #111827;
  margin-bottom: 0.75rem;
  /* 文本溢出省略 */
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  transition: color 0.2s ease;
}

.document-card:hover .document-title {
  color: #4f46e5;
}

.document-meta {
  margin-top: auto;
  font-size: 0.75rem;
  color: #6b7280;
  display: flex;
  align-items: center;
}

.document-date {
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

.document-date::before {
  content: '🕒';
  font-size: 0.875rem;
}

.document-card-actions {
  position: absolute;
  top: 0.75rem;
  right: 0.75rem;
  opacity: 0;
  transition: all 0.3s ease;
  transform: translateY(-5px);
  z-index: 2;
}

.document-card:hover .document-card-actions {
  opacity: 1;
  transform: translateY(0);
}

.delete-btn {
  padding: 0.375rem 0.75rem;
  background-color: #ef4444;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 0.75rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 5px rgba(239, 68, 68, 0.2);
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

.delete-btn::before {
  content: '🗑️';
  font-size: 0.875rem;
}

.delete-btn:hover {
  background-color: #dc2626;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(239, 68, 68, 0.3);
}

.delete-btn:disabled {
  background-color: #f3f4f6;
  color: #9ca3af;
  cursor: not-allowed;
  border: 1px solid #e5e7eb;
  box-shadow: none;
}

.disabled-btn {
  opacity: 0.5;
  pointer-events: none;
  transform: none !important;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 1.5rem;
  margin-top: 2.5rem;
  background-color: white;
  padding: 1rem;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  max-width: 400px;
  margin-left: auto;
  margin-right: auto;
}

.pagination-btn {
  padding: 0.625rem 1.25rem;
  background-color: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #4b5563;
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

.pagination-btn:hover:not(:disabled) {
  background-color: #f3f4f6;
  border-color: #9ca3af;
  transform: translateY(-2px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
  color: #111827;
}

.pagination-btn:disabled {
  opacity: 0.4;
  cursor: not-allowed;
}

.pagination-info {
  font-size: 0.875rem;
  font-weight: 500;
  color: #4b5563;
  background-color: #f3f4f6;
  padding: 0.5rem 1rem;
  border-radius: 6px;
}

/* 加载和空状态样式 */
.loading-placeholder,
.empty-state {
  padding: 4rem 2rem;
  text-align: center;
  color: #6b7280;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  margin: 2rem 0;
}

.empty-state p {
  margin-bottom: 1.5rem;
  font-size: 1.125rem;
  color: #4b5563;
}

.btn-primary {
  display: inline-block;
  padding: 0.75rem 1.75rem;
  background-color: #4f46e5;
  color: white;
  border: 1px solid #4f46e5;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  text-decoration: none;
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.2);
  position: relative;
  overflow: hidden;
  z-index: 1;
}

.btn-primary::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.1);
  transform: scaleX(0);
  transform-origin: right;
  transition: transform 0.3s ease;
  z-index: -1;
}

.btn-primary:hover {
  background-color: #4338ca;
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(79, 70, 229, 0.3);
}

.btn-primary:hover::before {
  transform: scaleX(1);
  transform-origin: left;
}
</style>